import sys, settings, msgs, time, getopt, getpass, hashlib, hmac, socket
import fcntl
import struct

def usage():
	print "whatever"

try:
    	opts, args = getopt.getopt(sys.argv[1:], "ho:u:s:k:t:", ["help", "opcode=", "user=", "server=", "keyfile=", "store="])
except getopt.GetoptError, err:
    	usage()
    	sys.exit(2)

opCode = user = password = key = server = serverKeyFile = None
for o, a in opts:
       	if o in ("-h", "--help"):
     		usage()
      		sys.exit(0)
        elif o in ("-o", "--opcode"):
      		opCode = a
	elif o in ("-u", "--user"):
		user = a
	elif o in ("-s", "--server"):
		server = a
	elif o in ("-k", "--keyfile"):
		serverKeyFile = a
        elif o in ("-t", "--store"):
		userKeyFile = a
        else:
       	    assert False, "unhandled option"

if opCode == "crtuser":
	fd = open(serverKeyFile, "r")
	key = fd.read().rstrip("\n")
	password = getpass.getpass("User password:")

	uh = hashlib.new('sha1')
	uh.update("%s:%s" % (user, password))
	userHash1 = uh.hexdigest()

	uhh = hashlib.new('sha1')
	uhh.update("%s" % (userHash1))
	userHash2 = uhh.hexdigest()

	ub = hmac.new(key)
	ub.update(userHash2)
	userBlob = ub.hexdigest()

	conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	conn.connect((server, 5023))

	data = "crtuser\r\n%s" % (userBlob)
	conn.send(data)
	conn.close()

	fd = open(userKeyFile, "a+")
	fd.write("%s\r\n" % (userHash1))
	fd.close()
